#!/usr/bin/env ruby -wKU
#encoding: UTF-8

require 'fileutils'
#require 'file'
#require 'dir'

#require 'backend/model/TNovel'
require 'backend/model/TVolume'
require 'backend/model/TChapter'

#require 'backend/crawler/TiebaCrawler'

module TiebaData
  
  class TChapterWriter
    
    def initialize(crawler)
      crawler.add_observer(self)
    end
    
    # save chapter content
    def update(chapters)
      
      chapters.each do |chp|
        
        volume = chp.volume
        # novel = volume.novel
        
        volumeDir = volume.storageDir
        FileUtils.makedirs(volumeDir) #unless Dir.exist? volumeDir
        
        chpPath = chp.storagePath
        
        # do nothing if already fetched
        # FIX issue
        # return if File.exists? chpPath
        next if File.exists? chpPath
        
        File.open(chpPath, 'w') do |file|
          file.flock(File::LOCK_EX)
          file.write(chp.content)
        end
      end
    end
    
  end
  
end
